package com.zhmksy.jwt_study.controller;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhmksy.jwt_study.entity.User;
import com.zhmksy.jwt_study.service.UserService;
import com.zhmksy.jwt_study.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhmsky
 * @date 2021/12/4 16:21
 */
@Controller
@EnableTransactionManagement
@ResponseBody
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/user/login")
    public Map<String,Object> login(String username,String password){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name",username).eq("password",password);
        User loginUser = userService.getOne(wrapper);
        HashMap<String, Object> map = new HashMap<>();
        //认证失败
        if(loginUser==null){
            map.put("state",false);
            map.put("msg","用户名或密码错误!");
        //认证成功
        }else{
            HashMap<String, String> userMap = new HashMap<>();
            userMap.put("username",loginUser.getName());
            userMap.put("age",loginUser.getAge().toString());
            userMap.put("email",loginUser.getEmail());
            String token = JwtUtils.getToken(userMap);
            map.put("token",token);
            map.put("state",true);
            map.put("msg","认证通过！");
        }
        return map;
    }

    @PostMapping("/user/test")
    public Map<String,Object> test(String token){
        HashMap<String, Object> map = new HashMap<>();
        try {
            DecodedJWT tokenInfo = JwtUtils.getTokenInfo(token);
            map.put("state",true);
            map.put("msg","请求成功!");
            return map;
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg","无效标签!");
        } catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("msg","token过期!");
        } catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg","算法不匹配!");
        } catch (Exception e){
            e.printStackTrace();
            map.put("msg","出现了严重异常!!");
        }
        map.put("state",false);
        return map;
    }

}
